﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Budget.DataAccess.Repository;

namespace Budget.DataAccess.Services
{
	public class MthDataService : IMthDataService
	{
		private IRepository<Mth> repo;

		public MthDataService( IRepository<Mth> repository )
		{
			repo = repository;
		}

		#region IMthDataService Members

		public IList<Mth> GetAll()
		{
			IList<Mth> mths;
			using ( repo )
			{
				mths = repo.Query().OrderBy( m => m.Year ).OrderBy( m => m.Month ).ToList();
			}
			return mths;
		}

		public Mth GetById( int mthId )
		{
			Mth mth;
			using ( repo )
			{
				mth = repo.Query().Where( m => m.MthId == mthId ).SingleOrDefault();// .OrderBy( m => m.Year ).OrderBy( m => m.Month ).ToList();
			}
			return mth;
		}

		public void Save( Mth month )
		{
			using ( repo )
			{
				if ( month.MthId == 0 )
				{
					repo.Add( month );
				}
				else
				{
					repo.Attach( month );
				}

				repo.SubmitChanges();
				
			}
		}

		public bool DoesMonthYearExist( int month, int year )
		{
			bool exists = false;
			
			using ( repo )
			{
				exists = repo.Query().Where( m => m.Month == month && m.Year == year ).Count() > 0;
			}

			return exists;
		}
		
		public Mth GetByMonthAndYear( int month, int year )
		{
			Mth mth;
			
			using ( repo )
			{
				mth = repo.Query().Where( m => m.Month == month && m.Year == year ).FirstOrDefault();
			}

			return mth;
		}

		public Mth GetPreviousMonth( int mthId )
		{
			Mth prevMth = null;

			using ( repo )
			{
				Mth currMth = repo.Query().Where( m => m.MthId == mthId ).FirstOrDefault();
				if ( currMth != null )
				{
					int cMonth = currMth.Month;
					int cYear = currMth.Year;
					int pMonth = cMonth > 1 ? cMonth - 1 : 12;
					int pYear = cMonth > 1 ? cYear : cYear - 1;

					prevMth = repo.Query().Where( m => m.Month == pMonth && m.Year == pYear ).FirstOrDefault();
				}
			}

			return prevMth;
		}

		#endregion
	}
}
